package freighttmpl

import (
	"context"
	"encoding/json"
	"strings"

	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/utils/pointy"
	"mall/service/setting/rpc/settingclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateFreightTemplateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateFreightTemplateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateFreightTemplateLogic {
	return &CreateFreightTemplateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateFreightTemplateLogic) CreateFreightTemplate(
	req *types.CreateFreightTemplateReq,
) (resp *types.BaseMsgResp, err error) {
	if req.Name == nil || len(strings.TrimSpace(*req.Name)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "setting.freightTemplateNameRequired"))
	}

	var restrictions []*settingclient.FreightTemplateRestrictionInfo
	if len(req.Restrictions) > 0 {
		for _, v := range req.Restrictions {
			regions, err := json.Marshal(v.Regions)
			if err != nil {
				logx.Errorw("CreateFreightTemplate FreightTemplateRestrictionInfo json.Marshal err", logx.Field("detail", err.Error()))
				continue
			}

			restrictions = append(restrictions, &settingclient.FreightTemplateRestrictionInfo{
				Regions:   pointy.GetPointer(string(regions)),
				Mode:      v.Mode,
				Threshold: v.Threshold,
				Sort:      v.Sort,
			})
		}
	}

	var rules []*settingclient.FreightTemplateRuleInfo
	if len(req.Rules) > 0 {
		for _, v := range req.Rules {
			regions, err := json.Marshal(v.Regions)
			if err != nil {
				logx.Errorw("CreateFreightTemplate FreightTemplateRuleInfo json.Marshal err", logx.Field("detail", err.Error()))
				continue
			}

			rules = append(rules, &settingclient.FreightTemplateRuleInfo{
				Regions:       pointy.GetPointer(string(regions)),
				FirstUnit:     v.FirstUnit,
				FirstPrice:    v.FirstPrice,
				ContinueUnit:  v.ContinueUnit,
				ContinuePrice: v.ContinuePrice,
				Sort:          v.Sort,
			})
		}
	}

	res, err := l.svcCtx.SettingRpc.BackendCreateFreightTemplate(l.ctx, &settingclient.FreightTemplateInfo{
		Name:         req.Name,
		Remark:       req.Remark,
		FreeShipping: req.FreeShipping,
		ChargeMode:   req.ChargeMode,
		Sort:         req.Sort,
		Status:       req.Status,
		Restrictions: restrictions,
		Rules:        rules,
	})
	if err != nil {
		return
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}
